package com.jjyu.controller;

import com.jjyu.entity.Coupon;
import com.jjyu.service.CouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/coupons")
public class CouponController {

    private final CouponService couponService;

    @Autowired
    public CouponController(CouponService couponService) {
        this.couponService = couponService;
    }

    // 获取所有优惠券
    @GetMapping
    public ResponseEntity<List<Coupon>> getAllCoupons() {
        List<Coupon> coupons = couponService.list();
        return ResponseEntity.ok(coupons);
    }

    // 根据ID获取单个优惠券
    @GetMapping("/{couponId}")
    public ResponseEntity<Coupon> getCouponById(@PathVariable int couponId) {
        Coupon coupon = couponService.getById(couponId);
        if (coupon != null) {
            return ResponseEntity.ok(coupon);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 添加优惠券
    @PostMapping
    public ResponseEntity<Coupon> addCoupon(@RequestBody Coupon coupon) {
        boolean result = couponService.addCoupon(coupon);
        if (result) {
            return ResponseEntity.ok(coupon);
        } else {
            return ResponseEntity.badRequest().body(null);
        }
    }

    // 更新优惠券
    @PutMapping("/{couponId}")
    public ResponseEntity<Coupon> updateCoupon(@PathVariable int couponId, @RequestBody Coupon coupon) {
        boolean result = couponService.updateCoupon(coupon);
        if (result) {
            return ResponseEntity.ok(coupon);
        } else {
            return ResponseEntity.badRequest().body(null);
        }
    }

    // 删除优惠券
    @DeleteMapping("/{couponId}")
    public ResponseEntity<String> removeCoupon(@PathVariable int couponId) {
        boolean result = couponService.removeCoupon(couponId);
        if (result) {
            return ResponseEntity.ok("Coupon removed successfully");
        } else {
            return ResponseEntity.badRequest().body("Failed to remove coupon");
        }
    }
}